package sk.openit.xml.stax.cursor;

import java.io.FileInputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import sk.openit.xml.entity.DbConfig;
import sk.openit.xml.entity.DbConfigTags;

public class DbConfigReader implements DbConfigTags {
	private DbConfig dbConfig;
    private String fileName = "database-config.xml";
	
	public DbConfigReader(String fileName) {
		this.fileName = fileName;
	}
	
    public void process() {
        XMLInputFactory xmlif = null;

        try {
            xmlif = XMLInputFactory.newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
        	XMLStreamReader xmlr = xmlif.createXMLStreamReader(fileName, new FileInputStream(fileName));
        	dbConfig = new DbConfig();
        	int eventType;
        	
        	//check if there are more events in the input stream
            while (xmlr.hasNext()) {            	
                eventType = xmlr.next();
            	if (XMLStreamReader.START_ELEMENT == eventType) {
            		processTag(xmlr);
            	}                
            }
        } catch (XMLStreamException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    
    private void processTag(XMLStreamReader xmlr) {
    	String tagName = xmlr.getName().toString();
		try {
	    	if (CONFIG.equals(tagName)) {
	    		dbConfig.setDbType(xmlr.getAttributeValue(null, DB_TYPE));    		
	    	} else if (HOST.equals(tagName)) {
					dbConfig.setHost(xmlr.getElementText());
	    	} else if (PORT.equals(tagName)) {
				dbConfig.setPort(xmlr.getElementText());    	
	    	} else if (INSTANCE.equals(tagName)) {
				dbConfig.setInstance(xmlr.getElementText());    	
	    	} else if (DATABASE.equals(tagName)) {
				dbConfig.setDatabase(xmlr.getElementText());    	
	    	} else if (USER.equals(tagName)) {
				dbConfig.setUser(xmlr.getElementText());    	
	    	}
		} catch (XMLStreamException e) {
			System.err.println("Unable to process tag: " + tagName);
			e.printStackTrace();
		}    	
	}

	public DbConfig getDbConfig() {
		return dbConfig;
	}
}
